package api.data.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import api.data.pojo.SysPermission;
import api.data.utils.JSONResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Api(tags = "基础接口")
@Slf4j
public class BaseController {
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverURL; //服务提供者的服务名

    protected JSONResult get_remote_data(String url,int page,int limit){
        int start = (page-1) * limit;
        String body = restTemplate.getForObject(serverURL + "/" + url + start + "/" + limit, String.class);
        JSONObject rs = (JSONObject) JSONObject.parse(body);
        if(rs.get("code").equals(0)){
            JSONObject data = (JSONObject)rs.get("data");
            int num = Integer.parseInt(data.get("num").toString());
            Object obj = data.get("data");
            return JSONResult.ok(num,obj);
        }else{
            return JSONResult.errorMsg("没有纪录");
        }
    }

    protected JSONObject get_remote_data_list_noformat(String url,Boolean isCache,Integer timeout){
        String key = DigestUtils.md5DigestAsHex(url.getBytes());
        String body = restTemplate.getForObject(serverURL + "/" + url,String.class);
        JSONObject rs = (JSONObject) JSONObject.parse(body);
        return rs;
    }

    protected JSONObject get_remote_data_list_nocache_noformat(String url,Boolean isCache,Integer timeout){
        String body = restTemplate.getForObject(serverURL + "/" + url,String.class);
        JSONObject rs = (JSONObject) JSONObject.parse(body);
        return rs;
    }


    protected JSONObject get_remote_data_list_noformat(String url,Boolean isCache){
        return get_remote_data_list_noformat(url,true,2000);
    }

    protected JSONObject get_remote_data_list_noformat(String  url){
        return get_remote_data_list_noformat(url,false,2000);
    }

    protected List<Object> get_remote_data_list(String url){
        String body = restTemplate.getForObject(serverURL + "/" + url,String.class);
        JSONObject rs = (JSONObject) JSONObject.parse(body);
        List<Object> list = new ArrayList<Object>();
        if(rs.get("code").equals(0)){
            return (List<Object>) rs.get("data");
        }else{
            return list;
        }
    }

    protected SysPermission getFontMenuObj(){
        //query/jqdata_price_1/select|cdate,open,close,low,high/where|code=@688301.XSHG@
        JSONObject rs = this.get_remote_data_list_noformat("query/index_menu/select|*/where|parent_id=@0@",true,6000);
        System.out.println(rs);
        String jsonString = "";
        SysPermission newt = new SysPermission();
        if(rs.getString("msg").equals("OK")){
            SysPermission t = new SysPermission();
            JSONArray arr = (JSONArray) rs.get("data");
            Map<String,Object> map = (Map<String, Object>) arr.get(0);
            t.setId((Integer) map.get("id"));
            t.setParentId((Integer) map.get("parent_id"));
            t.setName(String.valueOf(map.get("name")));
            t.setLevel((Integer) map.get("level"));
            t.setUrl(String.valueOf(map.get("url")));
            t.setIcon(String.valueOf(map.get("icon")));
            t.setChildren(new ArrayList<SysPermission>());
            newt = this.recursionFn(t,"index_menu");
        }
        return newt;
    }

    protected SysPermission getMenuObj(){
        //query/jqdata_price_1/select|cdate,open,close,low,high/where|code=@688301.XSHG@
        JSONObject rs = this.get_remote_data_list_noformat("query/sys_permission/select|*/where|parent_id=@0@",true,6000);
        System.out.println(rs);
        String jsonString = "";
        SysPermission newt = new SysPermission();
        if(rs.getString("msg").equals("OK")){
            SysPermission t = new SysPermission();
            JSONArray arr = (JSONArray) rs.get("data");
            Map<String,Object> map = (Map<String, Object>) arr.get(0);
            t.setId((Integer) map.get("id"));
            t.setParentId((Integer) map.get("parent_id"));
            t.setName(String.valueOf(map.get("name")));
            t.setLevel((Integer) map.get("level"));
            t.setUrl(String.valueOf(map.get("url")));
            t.setIcon(String.valueOf(map.get("icon")));
            t.setChildren(new ArrayList<SysPermission>());
            newt = this.recursionFn(t,"sys_permission");
        }
        return newt;
    }

    protected String getMenuStr() throws JsonProcessingException {
        SysPermission newt = this.getMenuObj();
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(newt);
        return jsonString;
    }

    /**
     * 递归
     */
    private SysPermission recursionFn(SysPermission t,String tablename) {
        // 得到子节点列表
        List<SysPermission> childList = getChildList(t,tablename);
        t.setChildren(childList);
        for (SysPermission tChild : childList) {
            if (hasChild(tChild,tablename)) {
                // 判断是否有子节点
                Iterator<SysPermission> it = childList.iterator();
                while (it.hasNext()) {
                    SysPermission n = (SysPermission) it.next();
                    recursionFn(n,tablename);
                }
            }
        }
        return t;
    }

    /**
     * 得到子节点列表
     */
    private List<SysPermission> getChildList(SysPermission t,String tablename) {
        List<SysPermission> tlist = new ArrayList<SysPermission>();
        JSONObject rs = this.get_remote_data_list_noformat("query/"+tablename+"/select|*/where|parent_id=@"+t.getId()+"@",true,6000);
        System.out.println(rs);
        if(rs.getString("msg").equals("OK")){
            List<Map<String,Object>> list = (List<Map<String, Object>>) rs.get("data");
            if(list.size() > 0){
                for(int i=0;i< list.size();i++){
                    SysPermission t1 = new SysPermission();
                    Map<String,Object> map = (Map<String, Object>) list.get(i);
                    System.out.println(map.toString());
                    t1.setId((Integer) map.get("id"));
                    t1.setParentId((Integer) map.get("parent_id"));
                    t1.setName(String.valueOf(map.get("name")));
                    t1.setLevel((Integer) map.get("level"));
                    t1.setUrl(String.valueOf(map.get("url")));
                    t1.setIcon(String.valueOf(map.get("icon")));
                    tlist.add(t1);
                }
                System.out.println(tlist.toString());
            }

        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(SysPermission t,String tablename) {
        return getChildList(t,tablename).size() > 0 ? true : false;
    }
}
